package cn.tsmchina.one.controller.m;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.tsmchina.one.service.order.OrderService;

/**
 * 微信支付
 */
@Controller
@RequestMapping("/wcpay")
public class WcPayController {
	@Autowired
	private OrderService orderService;
	
	/**
	 * 用户在成功完成支付后，微信后台通知（post）商户服务器（notify_url）支付结果。 
	 * 商户可以使用 notify_url 的通知结果进行个性化页面的展示。
	 */
	@RequestMapping(value="/notify",method= RequestMethod.POST)
	@ResponseBody
	public String notify(HttpServletRequest request){
		String orderId = request.getParameter("out_trade_no");//订单号
		String trade_state = request.getParameter("trade_state");//交易状态,支付结果：0—成功,其他保留
		if(!StringUtils.isEmpty(orderId) && !StringUtils.isEmpty(trade_state)){
			if("0".equals(trade_state)){
				//支付成功
				orderService.updatePayStatus(Long.valueOf(orderId));
				return "success";
			}
		}
		
		System.out.println("==== 微信支付失败通知："+request.getParameter("pay_info"));
		return "fail";
	}
	
	@RequestMapping("/requestOK")
	public String requestOK(String orderId,long cid,  HttpServletRequest request){
		System.out.println("for test requestOK**********************************************");
		if(!StringUtils.isEmpty(orderId)){
			//支付成功,同步更新支付状态
			orderService.updatePayStatus(Long.valueOf(orderId));			
		}
		return "redirect:/user/backend?cid=" + cid +"#mp.weixin.qq.com";
	}
}
